(function() {
  var crypto, express, iced, moment, pgsql, router, sendmail, __iced_k, __iced_k_noop;

  iced = require('iced-runtime');
  __iced_k = __iced_k_noop = function() {};

  express = require('express');

  pgsql = require('pg');

  crypto = require('crypto');

  moment = require('moment');

  sendmail = require('../lib/sendmail');

  router = express.Router();

  module.exports = router;

  router.get('/', function(req, res, next) {
    var client, done, err, result, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    if (req.session.userinfo && req.session.userinfo.uuid) {
      return res.redirect('/');
    }
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
        });
        pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              client = arguments[1];
              return done = arguments[2];
            };
          })(),
          lineno: 18
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          done(client);
          return next(err);
        }
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
          });
          client.query("update web_users set disabled = false, failed_cnt = 0, unlock_time = null where unlock_time is not null and unlock_time < CURRENT_TIMESTAMP", __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return result = arguments[1];
              };
            })(),
            lineno: 25
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (err) {
            done(client);
            return next(err);
          }
          done();
          return res.render('login');
        });
      };
    })(this));
  });

  router.post('/', function(req, res, next) {
    var client, content, done, err, password, result, sha1, unlock_time, user, ___iced_passed_deferral, __iced_deferrals, __iced_k;
    __iced_k = __iced_k_noop;
    ___iced_passed_deferral = iced.findDeferral(arguments);
    if (!req.body.username || !req.body.password) {
      res.locals.echo_title = '登陆失败';
      res.locals.echo_message = '用户名和密码不能为空，请重新登陆';
      return res.render('login');
    }
    (function(_this) {
      return (function(__iced_k) {
        __iced_deferrals = new iced.Deferrals(__iced_k, {
          parent: ___iced_passed_deferral,
          filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
        });
        pgsql.connect(settings.pgsql_url, __iced_deferrals.defer({
          assign_fn: (function() {
            return function() {
              err = arguments[0];
              client = arguments[1];
              return done = arguments[2];
            };
          })(),
          lineno: 38
        }));
        __iced_deferrals._fulfill();
      });
    })(this)((function(_this) {
      return function() {
        if (err) {
          done(client);
          return next(err);
        }
        (function(__iced_k) {
          __iced_deferrals = new iced.Deferrals(__iced_k, {
            parent: ___iced_passed_deferral,
            filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
          });
          client.query("select u.*, r.name as role_name, r.root as role_root, r.permission as permission from web_users as u left join web_roles as r on u.role = r.uuid where u.loginname = $1", [req.body.username], __iced_deferrals.defer({
            assign_fn: (function() {
              return function() {
                err = arguments[0];
                return result = arguments[1];
              };
            })(),
            lineno: 48
          }));
          __iced_deferrals._fulfill();
        })(function() {
          if (err) {
            done(client);
            return next(err);
          }
          (function(__iced_k) {
            if (result.rows.length < 1) {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                });
                client.query("select count(*) as count from web_users", __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      err = arguments[0];
                      return result = arguments[1];
                    };
                  })(),
                  lineno: 54
                }));
                __iced_deferrals._fulfill();
              })(function() {
                if (err) {
                  done(client);
                  return next(err);
                }
                done();
                if (parseInt(result.rows[0].count) === 0) {
                  if (req.body.username === 'root' && req.body.password === 'root') {
                    req.session.userinfo = {
                      serial: 0,
                      uuid: 'uuid',
                      loginname: 'root',
                      realname: '系统用户',
                      role_name: 'root',
                      role_root: true,
                      permission: {}
                    };
                    return req.session.save(function(err) {
                      return res.redirect('/');
                    });
                  }
                }
                res.locals.echo_title = '登陆失败';
                return res.render('login', {
                  echo_message: '用户名错误，请确认后重新登陆'
                });
                return __iced_k();
              });
            } else {
              return __iced_k();
            }
          })(function() {
            user = result.rows[0];
            if (user.disabled) {
              done();
              res.locals.echo_title = '登陆失败';
              return res.render('login', {
                echo_message: '该用户已被禁用，不允许登录...'
              });
            }
            sha1 = crypto.createHash('sha1');
            sha1.update(user.uuid);
            password = sha1.update(req.body.password.trim()).digest('hex');
            (function(__iced_k) {
              if (password !== user.password) {
                if (!user.lock_enable) {
                  res.locals.echo_title = '登录失败';
                  res.locals.echo_message = '密码错误，请重新登录';
                  return res.render('login');
                }
                (function(__iced_k) {
                  if (user.failed_cnt >= 4) {
                    unlock_time = moment().add(5, 'minutes');
                    console.log(unlock_time);
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral,
                        filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                      });
                      client.query("update web_users set disabled = true, unlock_time = $1 where uuid = $2", [unlock_time, user.uuid], __iced_deferrals.defer({
                        assign_fn: (function() {
                          return function() {
                            err = arguments[0];
                            return result = arguments[1];
                          };
                        })(),
                        lineno: 97
                      }));
                      __iced_deferrals._fulfill();
                    })(function() {
                      done();
                      res.locals.echo_title = '密码错误，登录失败';
                      res.locals.echo_message = '用户被锁定，您可以等待 5 分钟后自动解锁，或联系管理员帮助解锁';
                      res.locals.locked = true;
                      res.locals.wait_time = 5 * 60;
                      return res.render('login');
                      return __iced_k();
                    });
                  } else {
                    (function(__iced_k) {
                      __iced_deferrals = new iced.Deferrals(__iced_k, {
                        parent: ___iced_passed_deferral,
                        filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                      });
                      client.query("update web_users set failed_cnt = failed_cnt + 1 where uuid = $1", [user.uuid], __iced_deferrals.defer({
                        assign_fn: (function() {
                          return function() {
                            err = arguments[0];
                            return result = arguments[1];
                          };
                        })(),
                        lineno: 109
                      }));
                      __iced_deferrals._fulfill();
                    })(function() {
                      done();
                      res.locals.echo_title = '密码错误，登录失败';
                      res.locals.echo_message = ("您已连续登录失败 " + (user.failed_cnt + 1) + " 次，") + ("还剩 " + (4 - user.failed_cnt) + " 次尝试机会");
                      res.locals.retry_cnt = 4 - user.failed_cnt;
                      return res.render('login');
                      return __iced_k();
                    });
                  }
                })(__iced_k);
              } else {
                return __iced_k();
              }
            })(function() {
              (function(__iced_k) {
                __iced_deferrals = new iced.Deferrals(__iced_k, {
                  parent: ___iced_passed_deferral,
                  filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                });
                client.query("update web_users set failed_cnt = 0, unlock_time = null where uuid = $1", [user.uuid], __iced_deferrals.defer({
                  assign_fn: (function() {
                    return function() {
                      err = arguments[0];
                      return result = arguments[1];
                    };
                  })(),
                  lineno: 121
                }));
                __iced_deferrals._fulfill();
              })(function() {
                (function(__iced_k) {
                  __iced_deferrals = new iced.Deferrals(__iced_k, {
                    parent: ___iced_passed_deferral,
                    filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                  });
                  client.query("insert into web_login ( login_user, remote_ip, notes ) values ( $1, $2, $3 )", [user.uuid, req.ip, "" + user.realname + " 登录成功"], __iced_deferrals.defer({
                    assign_fn: (function() {
                      return function() {
                        err = arguments[0];
                        return result = arguments[1];
                      };
                    })(),
                    lineno: 130
                  }));
                  __iced_deferrals._fulfill();
                })(function() {
                  if (req.hostname === 'lucky-byte.com' && user.loginname === 'demo') {
                    content = "<p>登录时间: " + (moment().format('MM-DD HH:mm:ss')) + ".</p>\n<p>登录地址: " + req.ip + "</p>";
                    sendmail({
                      subject: 'DEMO 用户登录',
                      to: 'xiaohu xiaohu@lucky-byte.com',
                      html: content
                    });
                  }
                  req.session.userinfo = user;
                  req.session.userinfo.password = null;
                  if (!req.session.userinfo.permission) {
                    req.session.userinfo.permission = {};
                  }
                  (function(__iced_k) {
                    __iced_deferrals = new iced.Deferrals(__iced_k, {
                      parent: ___iced_passed_deferral,
                      filename: "/home/qiwei/Desktop/luckpay-web/coffee/routes/login.coffee"
                    });
                    client.query("delete from web_session where sess#>>'{userinfo, uuid}' = $1", [req.session.userinfo.uuid], __iced_deferrals.defer({
                      assign_fn: (function() {
                        return function() {
                          err = arguments[0];
                          return result = arguments[1];
                        };
                      })(),
                      lineno: 153
                    }));
                    __iced_deferrals._fulfill();
                  })(function() {
                    if (err) {
                      done(client);
                      return next(err);
                    }
                    done();
                    return req.session.save(function(err) {
                      var last_access;
                      if (err) {
                        return res.render('login', {
                          echo_message: '保存会话数据失败，请联系系统管理员'
                        });
                      }
                      last_access = req.session.last_access || '/';
                      delete req.session.last_access;
                      return res.redirect(last_access);
                    });
                  });
                });
              });
            });
          });
        });
      };
    })(this));
  });

}).call(this);
